<template>
  <view class="warehouse-container">
    <!-- 页面头部 -->
    <!-- <view class="page-header">
      <text class="page-title">出库红冲作业</text>
    </view> -->

    <!-- 出库红冲信息区域 -->
    <view class="info-section">
      <view class="section-header">
        <text class="section-title">单据信息</text>
      </view>

      <!-- 出库红冲类型标签页 -->
      <!-- <view class="in-type-tabs">
        <view
          class="tab-item"
          :class="{ active: currentInType === 'weigh' }"
          @click="switchInType('weigh')"
        >
          <text class="tab-text">缴库</text>
        </view>
      </view> -->

      <view class="info-form">
        <view class="form-item">
          <text class="form-label">单据日期</text>
          <picker
            class="form-picker"
            mode="date"
            :value="formData.inDate"
            @change="handleDateChange"
          >
            <view class="picker-content">
              <text>{{ formData.inDate }}</text>
              <text class="picker-arrow">></text>
            </view>
          </picker>
        </view>
        <view class="form-item">
          <text class="form-label">目标仓库</text>
          <view class="warehouse-display">{{
            currentWarehouse ? currentWarehouse.warehouseName : "请选择"
          }}</view>
        </view>
      </view>
    </view>

    <!-- 待出库红冲区域 -->
    <view class="search-section">
      <view class="search-form">
        <view class="section-header">
          <view class="title-wrapper">
            <text class="section-title">待提交</text>
          </view>
          <!-- 统一输入框 -->
          <input
            ref="materialInput"
            v-model="searchForm.searchCode"
            class="material-input"
            type="text"
            placeholder="请输入单据"
            @keyup.enter="searchPackPrintRecords"
            @confirm="searchPackPrintRecords"
            :disabled="!inputMethodEnabled"
            autocomplete="off"
            spellcheck="false"
          />

          <button class="scan-btn" @click="searchPackPrintRecords">查询</button>
        </view>

        <!-- 提示文本和输入法开关在同一行 -->
        <view
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 8rpx;
          "
        >
          <text class="section-subtitle" style="font-size: 24rpx; color: #999"
            >红冲回成品库，只允许单笔冲销</text
          >

          <!-- 输入法开关 -->
          <view class="input-switch-container">
            <text class="switch-label"
              >输入法{{ inputMethodEnabled ? "开启" : "关闭" }}</text
            >
            <view
              class="custom-switch-wrapper"
              @click="handleInputMethodSwitchChange"
            >
              <view
                class="custom-switch"
                :class="{ 'custom-switch-active': inputMethodEnabled }"
              >
                <view
                  class="custom-switch-handle"
                  :class="{ 'custom-switch-handle-active': inputMethodEnabled }"
                ></view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 待提交表格 -->
    <view v-if="packPrintRecords.length > 0" class="material-table-section">
      <view class="table-body">
        <view class="table-row header">
          <view class="table-cell">选择</view>
          <view class="table-cell">钢种</view>
          <view class="table-cell">规格</view>
          <view class="table-cell">净重(KG)</view>
          <view class="table-cell">箱号</view>
          <view class="table-cell">轴号</view>
        </view>
        <view
          v-for="(item, index) in packPrintRecords"
          :key="index"
          class="table-row"
          :class="{
            selected: isRecordSelected(item),
          }"
          @click="toggleRecordSelection(item, index)"
        >
          <view class="table-cell">
            <text v-if="isRecordSelected(item)" class="check-icon">✓</text>
            <text v-else class="uncheck-icon">○</text>
          </view>
          <view class="table-cell">{{ item.steelGrade || "-" }}</view>
          <view class="table-cell">{{ item.spec || "-" }}</view>
          <view class="table-cell">{{
            (item.weightOfNet || 0).toFixed(3)
          }}</view>
          <view class="table-cell">{{ item.boxCode || "-" }}</view>
          <view class="table-cell">{{ item.axisCode || "-" }}</view>
        </view>
      </view>
    </view>
    <!-- 统计信息 -->
    <view class="material-table-section">
      <view class="statistics-section">
        <view class="stat-item">
          <text class="stat-label">选中记录数</text>
          <text class="stat-value">{{ selectedRecords.length }}</text>
        </view>
        <view class="stat-item">
          <text class="stat-label">总重量</text>
          <text class="stat-value">{{ totalWeight.toFixed(3) }} KG</text>
        </view>
      </view>
      <!-- 底部操作栏 -->
      <view class="action-bar">
        <view class="action-row">
          <button class="btn-reset" @click="resetForm">重置</button>
          <button class="btn-submit" @click="handleManualSubmit">提交</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// 导入API方法
import { ProdStockOutApi } from "@/api/warehouse/prodstockout";
import { ProdStockRealApi } from "@/api/warehouse/prodstockreal";

// 导入PDA扫码功能
import { pdaScanApi } from "@/pages/smart/pdaScan";

export default {
  name: "InWarehouseCreate",
  // 混入PDA扫码功能
  mixins: [pdaScanApi],
  data() {
    return {
      // 出库红冲类型配置
      inTypeOptions: [{ value: "manual", label: "生产出库红冲" }],
      inTypeIndex: 0,

      // 表单数据
      formData: {
        inType: "weigh",
        inDate: this.getCurrentDate(),
        warehouseId: "",
        warehouseName: "",
      },

      // 搜索表单
      searchForm: {
        searchCode: "",
      },

      // 输入法开关
      inputMethodEnabled: true,

      // 数据列表
      currentWarehouse: null,

      // 包装打印记录数据
      packPrintRecords: [], // 包装打印记录列表
      selectedRecords: [], // 选中的记录列表（支持多选）

      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        startDate: "", // 开始日期
        endDate: "", // 结束日期
      },
    };
  },

  computed: {
    currentInType() {
      return this.inTypeOptions[this.inTypeIndex]?.value;
    },

    totalWeight() {
      // 根据选中的记录计算总重量
      const total = this.selectedRecords.reduce(
        (sum, item) => sum + (Number(item.weightOfNet) || 0),
        0
      );
      return Number(total.toFixed(3));
    },
  },

  mounted() {
    this.loadInitialData();

    // 初始化输入法状态
    this.initInputMethod();

    // 启动PDA扫码（如果设备支持）
    this.startPdaContinuousScan();
  },

  beforeDestroy() {
    // 停止PDA扫码，释放资源
    this.stopPdaScan();
  },

  methods: {
    // 打印测试
    async handlePdaPrint() {
      try {
        console.log("开始打印测试...");

        const result = this.pdaPrint(
          "B20251019",
          "测试备注1",
          "备注2",
          "备注3"
        );

        if (result) {
          this.$modal.alert({
            content: "打印成功",
            title: "提示",
          });
        } else {
          this.$modal.alert({
            content: "打印失败，请检查打印机状态",
            title: "错误",
          });
        }
      } catch (error) {
        console.error("打印测试异常:", error);
        this.$modal.alert({
          content: "打印测试异常：" + error.message,
          title: "错误",
        });
      }
    },
    /**
     * 获取当前是否为自动提交模式
     * 规则：
     * - 任何模式下达到5笔都会触发自动提交
     */
    getIsAutoSubmitMode() {
      return true;
    },

    // 获取当前日期
    getCurrentDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },

    // 加载初始数据
    async loadInitialData() {
      try {
        // 加载当前用户仓库
        const warehouseRes = await this.getCurrentWarehouse();
        if (warehouseRes) {
          this.currentWarehouse = warehouseRes;
          this.formData.warehouseId = warehouseRes.warehouseId;
          this.formData.warehouseName = warehouseRes.warehouseName;
        }
      } catch (error) {
        console.error("加载初始数据失败:", error);
      }
    },

    // 获取当前用户仓库
    async getCurrentWarehouse() {
      try {
        // 从Vuex store获取用户配置的仓库信息
        const userConfig = this.$store.state.user.userConfig;
        if (userConfig && userConfig.wmName) {
          return {
            warehouseId: userConfig.warehouseId || "DEFAULT",
            warehouseName: userConfig.wmName,
          };
        }
      } catch (error) {
        console.error("获取用户仓库失败:", error);
      }

      // 默认值
      return {
        warehouseId: "DEFAULT",
        warehouseName: "默认仓库",
      };
    },

    // 初始化输入法状态
    initInputMethod() {
      // 从本地存储读取输入法状态
      const saved = uni.getStorageSync("inputMethodEnabled");
      if (saved !== null && saved !== undefined) {
        this.inputMethodEnabled = saved;
      }
    },

    /**
     * 启动PDA连续扫码
     * 在输入法关闭时启用PDA扫码，开启时使用输入法
     */
    startPdaContinuousScan() {
      // 只有在输入法关闭时才启用PDA扫码
      if (!this.inputMethodEnabled) {
        const success = this.startPdaScan((barcode) => {
          // 扫码结果处理
          this.handleScanResult(barcode);
        });

        if (success) {
          console.log("PDA连续扫码已启动");
        } else {
          console.warn("PDA扫码启动失败，将使用手动输入模式");
        }
      }
    },

    /**
     * 处理扫码结果
     * @param {string} barcode - 扫码得到的条码内容
     */
    handleScanResult(barcode) {
      if (!barcode) return;

      console.log("PDA扫码结果:", barcode);

      // 将扫码结果赋值给搜索框
      this.searchForm.searchCode = barcode;

      // 自动执行查询
      this.searchPackPrintRecords();
    },

    // 清除原表格中的选中状态
    clearOriginalTableSelection() {
      this.materialTable.forEach((item) => {
        if (item.isCheck) {
          this.$set(item, "isCheck", false);
          this.$set(item, "showError", false);
          this.$set(item, "prod_count", 0);
          this.$set(item, "trans_count", 0);
        }
      });
    },

    // 处理返回按钮点击
    handleBack() {
      // 检查是否有未出库红冲的数据
      if (this.materialList.length > 0) {
        uni.showModal({
          title: "提示",
          content: "有数据未出库红冲，请先提交出库红冲或删除待出库红冲数据",
          confirmText: "去提交",
          cancelText: "删除数据",
          success: (res) => {
            if (res.confirm) {
              // 用户选择去提交，不做任何操作
              return;
            } else if (res.cancel) {
              // 用户选择删除数据，清空materialList
              this.materialList = [];
              // 同时清除原表格中的选中状态
              this.clearOriginalTableSelection();
              // 返回上一页
              uni.navigateBack();
            }
          },
        });
      } else {
        // 没有数据，直接返回
        uni.navigateBack();
      }
    },

    // 重置所有查询结果表
    resetQueryResults() {
      // 重置合同表
      this.contractTable = [];
      this.showContractTable = false;

      // 重置检斤表
      this.weightTable = [];
      this.showWeightTable = false;
      this.selectedWeightRow = null;

      // 重置物料表
      this.materialTable = [];

      // 重置物料编码和名称输入
      this.materialCode = "";
      this.materialName = "";

      // 重置时间筛选
      this.timeFilter = "today";
    },

    // 日期变更
    handleDateChange(e) {
      // 获取选择的日期
      const selectedDate = e.detail.value;
      // 获取当前时间，保持时分秒
      const now = new Date();
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");
      // 组合成完整的日期时间格式
      this.formData.inDate = `${selectedDate} ${hours}:${minutes}:${seconds}`;
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        searchCode: "",
      };
      this.packPrintRecords = [];
      this.selectedRecords = [];
    },

    // 聚焦到输入框（输入法开启时弹出键盘）
    focusInput() {
      if (this.inputMethodEnabled && this.$refs.materialInput) {
        this.$nextTick(() => {
          if (this.$refs.materialInput.focus) {
            this.$refs.materialInput.focus();
          }
        });
      }
    },

    // 输入法开关切换处理
    handleInputMethodSwitchChange() {
      this.inputMethodEnabled = !this.inputMethodEnabled;

      // 保存到本地存储
      uni.setStorageSync("inputMethodEnabled", this.inputMethodEnabled);

      // 如果开启输入法，聚焦输入框
      if (this.inputMethodEnabled) {
        this.focusInput();
        // 停止PDA扫码
        this.stopPdaScan();
      } else {
        // 如果关闭输入法，启动PDA扫码
        this.startPdaContinuousScan();
      }
    },

    // 搜索包装打印记录
    async searchPackPrintRecords() {
      try {
        uni.showLoading({ title: "查询中..." });
        this.packPrintRecords = []; // 红冲只允许一个个冲销
        //若目标仓库是粗丝，则查询箱号，否则查询轴号
        let boxCode = this.searchForm.searchCode || undefined;
        let axisCode = this.searchForm.searchCode || undefined;
        // 当searchCode 包含SD开发的字符串时，按照大箱号查询，否则按照轴号查询,C 开头箱号
        if (
          this.searchForm.searchCode.includes("SD") ||
          this.searchForm.searchCode.includes("C") ||
          this.currentWarehouse?.warehouseName === "细丝"
        ) {
          axisCode = "";
        } else {
          boxCode = "";
        }
        const params = {
          boxCode: boxCode,
          axisCode: axisCode,
          // productType: this.currentWarehouse?.warehouseName,
        };

        const res = await ProdStockRealApi.getProdStockRealPDA(params);

        if (res.code === 0) {
          const newRecords = res.data || [];

          // 依据返回的productType 判断 细丝按照箱号汇总，其他按照轴号汇总给packPrintRecords
          let processedRecords = [];
          if (
            this.currentWarehouse?.warehouseName === "细丝" ||
            this.searchForm.searchCode.includes("C")
          ) {
            processedRecords = newRecords.reduce((acc, cur) => {
              const existing = acc.find((item) => item.boxCode === cur.boxCode);
              if (existing) {
                existing.weightOfNet = Number(
                  (existing.weightOfNet + cur.weightOfNet).toFixed(3)
                );
              } else {
                acc.push({ ...cur });
              }
              return acc;
            }, []);
          } else {
            processedRecords = newRecords.reduce((acc, cur) => {
              const existing = acc.find(
                (item) => item.axisCode === cur.axisCode
              );
              if (existing) {
                existing.weightOfNet = Number(
                  (existing.weightOfNet + cur.weightOfNet).toFixed(3)
                );
              } else {
                acc.push({ ...cur });
              }
              return acc;
            }, []);
          }

          // 检查重复项
          const duplicateRecords = [];
          const uniqueRecords = [];

          processedRecords.forEach((record) => {
            let isDuplicate = false;

            // 根据仓库类型判断重复
            if (this.currentWarehouse?.warehouseName === "细丝") {
              // 细丝依据箱号判断
              isDuplicate = this.packPrintRecords.some(
                (existing) => existing.boxCode === record.boxCode
              );
            } else {
              // 其他依据轴号判断
              isDuplicate = this.packPrintRecords.some(
                (existing) => existing.axisCode === record.axisCode
              );
            }

            if (isDuplicate) {
              duplicateRecords.push(record);
            } else {
              uniqueRecords.push(record);
            }
          });

          // 显示重复项提示
          if (duplicateRecords.length > 0) {
            uni.showToast({
              title: `${duplicateRecords.length}条记录已在待出库红冲清单中`,
              icon: "none",
              duration: 2000,
            });
          }

          // 只添加不重复的记录
          this.packPrintRecords = [...this.packPrintRecords, ...uniqueRecords];

          // 保留之前已选中的记录，同时选中新查询的记录
          if (uniqueRecords.length > 0) {
            console.log(
              "【查询后选中】新查询到" + uniqueRecords.length + "条记录"
            );
            console.log(
              "【查询后选中】当前已选中" +
                this.selectedRecords.length +
                "条记录"
            );

            // 合并之前选中的记录和新查询的记录，避免重复
            const allSelectedRecords = [...this.selectedRecords];
            uniqueRecords.forEach((newRecord) => {
              // 根据仓库类型判断重复：细丝按箱号，其他按轴号
              const isDuplicate =
                this.currentWarehouse?.warehouseName === "细丝"
                  ? allSelectedRecords.some(
                      (item) => item.boxCode === newRecord.boxCode
                    )
                  : allSelectedRecords.some(
                      (item) => item.axisCode === newRecord.axisCode
                    );

              if (!isDuplicate) {
                allSelectedRecords.push(newRecord);
              }
            });
            this.selectedRecords = allSelectedRecords;

            console.log(
              "【查询后选中】合并后总记录数:" + this.selectedRecords.length
            );

            // 检查是否达到5条数据，如果是则自动提交
            // if (this.selectedRecords.length === 5) {
            //   console.log("【查询后选中】达到5条记录，准备自动提交");
            //   // 延迟一下再自动提交，让用户能看到选择效果
            //   setTimeout(() => {
            //     console.log("【查询后选中】延迟结束，开始自动提交");
            //     this.autoSubmitForm();
            //   }, 500);
            // }
          }

          // 查询完成后清空输入框，便于下次输入,冲销不清空
          // this.searchForm.searchCode = "";

          // 重新聚焦到输入框
          this.$nextTick(() => {
            if (this.inputMethodEnabled) {
              this.focusInput();
            }
          });

          // 显示查询结果提示
          if (uniqueRecords.length > 0) {
            uni.showToast({
              title: `查询到${uniqueRecords.length}条新记录，已自动选中`,
              icon: "success",
            });
          } else if (duplicateRecords.length > 0) {
            // 如果所有记录都重复，只显示重复提示
            uni.showToast({
              title: `所有记录已在待出库红冲清单中`,
              icon: "none",
              duration: 2000,
            });
          }
        }
      } catch (error) {
        console.error("查询包装打印记录失败:", error);
        uni.showToast({ title: "查询失败，请重试", icon: "none" });
      } finally {
        uni.hideLoading();
      }
    },

    // 判断记录是否被选中
    isRecordSelected(record) {
      return this.selectedRecords.some((item) => item.id === record.id);
    },

    // 切换记录选中状态
    toggleRecordSelection(record, index) {
      console.log("【手动选中】切换记录选中状态，记录ID:" + record.id);

      const existingIndex = this.selectedRecords.findIndex(
        (item) => item.id === record.id
      );

      if (existingIndex !== -1) {
        // 如果已选中，则取消选中
        console.log(
          "【手动选中】取消选中记录，当前选中数:" +
            (this.selectedRecords.length - 1)
        );
        this.selectedRecords.splice(existingIndex, 1);
      } else {
        // 否则添加到选中列表
        console.log(
          "【手动选中】添加选中记录，当前选中数:" +
            (this.selectedRecords.length + 1)
        );
        this.selectedRecords.push({ ...record });

        // 检查是否达到5条数据，如果是则自动提交
        if (this.selectedRecords.length === 5) {
          console.log("【手动选中】达到5条记录，准备自动提交");
          // 延迟一下再自动提交，让用户能看到选择效果
          setTimeout(() => {
            console.log("【手动选中】延迟结束，开始自动提交");
            this.autoSubmitForm();
          }, 500);
        }
      }
    },

    // 获取当前是否为自动提交模式
    getIsAutoSubmitMode() {
      // 任何模式下达到5笔都会触发自动提交
      return true;
    },

    // 自动提交表单（扫码5笔数据自动出库红冲）
    async autoSubmitForm() {
      console.log("【自动提交】开始执行自动提交");

      // 执行自动提交，传入自动提交标志
      console.log("【自动提交】调用submitForm方法");
      await this.submitForm(true);
    },

    // 处理手动提交按钮点击
    handleManualSubmit() {
      console.log("【手动提交】用户点击提交出库红冲按钮");
      // 手动提交模式下，isAutoSubmit为false
      this.submitForm(false);
    },

    // 重置表单
    resetForm() {
      this.formData.inDate = this.getCurrentDate();
      this.resetSearch();
    },

    /**
     * 提交表单
     * @param {boolean} isAutoSubmit - 是否为自动提交
     *  - true: 自动提交（达到5笔数据时触发）
     *  - false: 手动提交（用户点击提交按钮触发）
     */
    async submitForm(isAutoSubmit = false) {
      console.log("【提交表单】", this.formData, "isAutoSubmit:", isAutoSubmit);

      // 显示加载状态
      uni.showLoading({
        title: isAutoSubmit ? "正在自动提交..." : "正在提交...",
        mask: true,
      });

      try {
        // 验证：必填字段检查
        const validation = this.validateForm();
        if (!validation.valid) {
          uni.hideLoading();
          uni.showToast({
            title: validation.message,
            icon: "none",
            duration: 2000,
          });
          return;
        }

        // 提交前确认（自动提交模式下跳过确认）
        if (!isAutoSubmit) {
          const confirmRes = await this.showSubmitConfirm();
          if (!confirmRes) {
            uni.hideLoading();
            return;
          }
        }

        //// 构建提交数据
        // 如果searchForm.searchCode包含C开头的则赋值给boxCode,productType为细丝，否则赋值给axisCode
        let boxCode = "";
        let axisCode = "";
        let productType = "";
        if (this.searchForm.searchCode.startsWith("C")) {
          boxCode = this.searchForm.searchCode;
          productType = "细丝";
        } else {
          axisCode = this.searchForm.searchCode;
          productType = "粗丝";
        }
        const submitData = [
          {
            boxCode: boxCode,
            axisCode: axisCode,
            productType: productType,
            isLoadBigBox: "否",
          },
        ];

        // 测试数据：[{"boxCode": "C2511022067", "axisCode": "", "productType": "细丝", "isLoadBigBox": "否"}]
        // const submitData = [{"boxCode": "C2510131012", "axisCode": "S25101310081", "productType": "细丝", "isLoadBigBox": "否"}];
        console.log("提交出库红冲数据:", submitData);

        // 调用实际的后端API 红冲出库
        const response = await ProdStockOutApi.deleteProdStockOut(submitData);

        // 隐藏加载状态
        uni.hideLoading();

        if (response.code === 0) {
          //遍历response.data,若data.boxCode有值，则将改行的msg信息添加到successMessages数组中，
          // 若data.axisCode有值，则将该行的msg信息添加到successMessages数组中
          const successMessages = [];
          response.data.forEach((item) => {
            if (item.boxCode) {
              successMessages.push(item.msg);
            }
            if (item.axisCode) {
              successMessages.push(item.msg);
            }
          });

          // 显示成功消息
          if (successMessages.length > 0) {
            const message = successMessages.join("；");
            uni.showToast({
              title: message,
              icon: "errorMsg",
              duration: 5000,
            });
          } else {
            uni.showToast({
              title: "出库红冲成功",
              icon: "success",
              duration: 2000,
            });
          }
        } else {
          // 处理失败
          await this.handleSubmitException({
            message: response.msg || "提交入库红冲失败",
          });
        }
      } catch (error) {
        console.error("提交出库红冲失败:", error);

        // 隐藏加载状态
        uni.hideLoading();

        // 处理异常
        await this.handleSubmitException(error);
      }
    },

    // 表单验证
    validateForm() {
      if (!this.formData.warehouseName) {
        return { valid: false, message: "请选择仓库" };
      }

      if (!this.formData.inDate) {
        return { valid: false, message: "请选择出库红冲日期" };
      }

      if (this.selectedRecords.length === 0) {
        return { valid: false, message: "请选择要出库红冲的记录" };
      }

      return { valid: true };
    },

    // 验证数字有效性
    isValidNumber(value) {
      return (
        value !== null &&
        value !== undefined &&
        !isNaN(value) &&
        isFinite(value)
      );
    },

    // 显示提交确认
    showSubmitConfirm() {
      return new Promise((resolve) => {
        const recordCount = this.selectedRecords.length;
        const totalWeight = this.totalWeight;

        uni.showModal({
          title: "确认提交",
          content: `共${recordCount}条记录，总重量：${totalWeight}KG，是否确认提交出库红冲？`,
          confirmText: "确认",
          cancelText: "取消",
          success: (res) => {
            resolve(res.confirm);
          },
        });
      });
    },

    // 处理提交成功
    async handleSubmitSuccess(res) {
      uni.showToast({
        title: "出库红冲单创建成功",
        icon: "success",
        duration: 2000,
      });

      // 记录成功日志
      console.log("出库红冲单创建成功:", res.data);

      // 重置表单
      this.resetForm();
    },

    // 处理提交异常
    async handleSubmitException(error) {
      console.error("提交表单异常:", error);

      let errorMsg = "提交失败，请重试";

      // 网络错误处理
      if (error.message && error.message.includes("Network")) {
        errorMsg = "网络连接失败，请检查网络后重试";
      } else if (error.code === "ECONNABORTED") {
        errorMsg = "请求超时，请稍后重试";
      } else if (error.response && error.response.status) {
        switch (error.response.status) {
          case 400:
            errorMsg = "请求参数错误，请检查输入数据";
            break;
          case 401:
            errorMsg = "登录已过期，请重新登录";
            break;
          case 403:
            errorMsg = "没有权限执行此操作";
            break;
          case 500:
            errorMsg = "服务器错误，请稍后重试";
            break;
          default:
            errorMsg = `服务器错误 (${error.response.status})，请稍后重试`;
        }
      }

      uni.showModal({
        title: "提交失败",
        content: errorMsg,
        showCancel: false,
        confirmText: "知道了",
      });
    },
  },
};
</script>

<style scoped lang="scss">
@import "~@/pages/smart/scss/create.scss";
</style>
